import { SourceObject, SourceImport } from '../types';
import { sourceImporters } from './importers';
import { SourceInitError } from '../../framework/utils/AppError';

export class SourceRegistry {
  private sources: SourceObject | null = null;
  private importers: SourceImport[] = sourceImporters;

  async initialize(): Promise<SourceObject> {
    if (this.sources) return this.sources;

    try {
      const modules = await Promise.all(
        this.importers.map(importer => importer())
      );

      this.sources = modules.reduce((acc, module) => ({
        ...acc,
        ...module.default
      }), {} as SourceObject);

      return this.sources;
    } catch (error) {
      console.error('Failed to initialize sources:', error);
      throw new SourceInitError('Source initialization failed');
    }
  }

  getSources(): SourceObject {
    if (!this.sources) {
      throw new SourceInitError('Sources not initialized. Call initialize() first.');
    }
    return this.sources;
  }

  /**
   * 添加一个重新加载的方法，用于开发时热重载
   * @returns 
   */
  async reload(): Promise<SourceObject> {
    this.sources = null;
    return this.initialize();
  }
}

// 创建单例实例
export const sourceRegistry = new SourceRegistry();